<?php

namespace plugin\exportcenter\app\queue\redis;

use Exception;
use plugin\exportcenter\app\logic\ExportLogic;
use plugin\exportcenter\app\model\Export;
use plugin\exportcenter\app\service\ExportManager;
use Webman\RedisQueue\Consumer;

class ExportCsv implements Consumer
{
    // 要消费的队列名
    public $queue = 'export-csv';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        // 无需反序列化
        $data = Export::where('id', $data['id'])->find()->toArray();
        if (!$data) {
            return;
        }
        $id = $data['id'];
        $logic = new ExportLogic();
        if (!$data['action']) {
            $logic->updateExportError($id, "未找到[{$data['action']}]导出类");
            return;
        }
        $action = ExportManager::getInstance()->get($data['action']);
        if (is_null($action)){
            $logic->updateExportError($id, "未找到[{$data['action']}]导出类");
            return;
        }

        $logic->updateExportStart($id);
        try {
            $ossUrl = $action->export($id, $data);
            $logic->updateExportSuccess($id, $ossUrl);
        } catch (Exception $exception) {
            $logic->updateExportError($id, $exception->getMessage());
        }
    }
}
